<template>
  <div>
    <basic-page-vxe
      ref="basePage"
      :columns="basicData.columns"
      :search-form="basicData.searchForm"
      :search-handle="basicData.searchHandle"
      list-api="querySysRole"
      export-api="exportSysRole"
      :export-name="$route.meta.title"
      del-api="deleteSysRole"
    />
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="90px" style="width: 100%">
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="temp.roleCode" placeholder="请输入" :disabled="dialogStatus==='update'" minlength="3" maxlength="64" clearable />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="temp.roleName" placeholder="请输入" :disabled="dialogStatus==='update'" minlength="3" maxlength="64" clearable />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDescription">
          <el-input v-model="temp.roleDescription" placeholder="请输入" maxlength="100" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="菜单授权" :visible.sync="showMenu" width="500px">
      <div style="height: 500px;overflow: auto">
        <el-tree
          ref="menu"
          default-expand-all
          :data="menuList"
          show-checkbox
          node-key="id"
          :default-checked-keys="defaultChecked"
          :props="defaultProps"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="checkAll('menu')">
          全选
        </el-button>
        <el-button @click="showMenu = false">
          取消
        </el-button>
        <el-button type="primary" @click="checkAth">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="按钮权限" :visible.sync="menuButtonTreeDialogFormVisible" width="600px">
      <div style="height: 500px;overflow: auto">
        <el-tree ref="menuButtonTreeRef" :data="menuButtonTree" show-checkbox node-key="key" highlight-current :props="defaultProps" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="checkAll('menuButtonTreeRef')">
          全选
        </el-button>
        <el-button @click="showMenu = false">
          取消
        </el-button>
        <el-button type="primary" @click="createAuthorizeMenuButton">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSysRole, updateSysRole, querySysMenuTree, queryMenuIdByRoleId, authorizeMenuToRole, queryMenuButtonByRoleCode, querySysMenuButtonTree, authorizeMenuButtonToRole } from '@/api/authority'
import qs from 'qs'
import { mapGetters } from 'vuex'

export default {
  name: '',
  components: {
  },
  directives: {},
  filters: {},
  data() {
    return {
      basicData: {
        columns: [
          { config: { title: '角色编码', field: 'roleCode' }},
          { config: { title: '角色名称', field: 'roleName' }, type: 'copy' },
          { config: { title: '角色描述', field: 'roleDescription' }},
          { config: { title: '创建日期', width: '160', field: 'createTime' }, type: 'time' },
          { config: { title: '操作', width: '390', field: 'opt' }, type: 'render',
            render: (h, scope) => {
              if ((scope.row.roleCode === 'ROLE_ADMIN' || scope.row.roleCode === 'ROLE_DEV')) {
                return (
                  <div>
                    <el-button plain size='mini' type='default' v-permission="'update'" onClick={() => this.handleUpdate(scope.row)}><i class='el-icon-edit'></i> 编辑</el-button>
                    <el-button plain size='mini' type='primary' v-permission="'authorize'" onClick={() => this.handleAuthorizeMenu(scope.row)}><i class='el-icon-s-check'></i> 授权菜单</el-button>
                    <el-button plain size='mini' type='warning' v-permission="'authorize'" onClick={() => this.handleAuthorizeMenuButton(scope.row.roleCode)}><i class='el-icon-s-check'></i> 授权按钮</el-button>
                  </div>
                )
              } else {
                return (
                  <div>
                    <el-button plain size='mini' type='default' v-permission="'update'" onClick={() => this.handleUpdate(scope.row)}><i class='el-icon-edit'></i> 编辑</el-button>
                    <el-button plain size='mini' type='primary' v-permission="'authorize'" onClick={() => this.handleAuthorizeMenu(scope.row)}><i class='el-icon-s-check'></i> 授权菜单</el-button>
                    <el-button plain size='mini' type='warning' v-permission="'authorize'" onClick={() => this.handleAuthorizeMenuButton(scope.row.roleCode)}><i class='el-icon-s-check'></i> 授权按钮</el-button>
                    <el-button plain size='mini' type='danger' v-permission="'delete'" onClick={() => this.$refs.basePage.handleDelete(scope.row)}><i class='el-icon-delete'></i> 删除</el-button>
                  </div>
                )
              }
            }
          }
        ],
        searchData: {},
        searchForm: [
          { type: 'Input', label: '角色名称', prop: 'username', width: '180px' }
        ],
        searchHandle: [
          { label: '新增', type: 'success', icon: 'el-icon-plus', permission: 'add', handle: () => { this.handleCreate() } }
        ]

      },
      temp: {
        id: undefined,
        status: 1,
        prefix: '86'
      },
      temButton: {},
      dialogFormVisible: false,
      showMenu: false,
      menuButtonTreeDialogFormVisible: false,
      dialogStatus: '',
      menuRow: {},
      roleCode: '',
      menuButtonTree: [],
      defaultChecked: [],
      menuList: [],
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        roleCode: [{ required: true, message: '请输入角色编码！', trigger: 'blur' }],
        roleName: [{ required: true, message: '请输入角色名称！', trigger: 'blur' }]
      },
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  computed: {
    ...mapGetters([
      'curAth'
    ])
  },
  created() {
    this.getType()
  },
  mounted() {
  },
  methods: {
    // 业务逻辑
    getType() {
      querySysMenuTree().then(response => {
        this.menuList = response.data
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addSysRole(this.temp).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
            this.handleReset()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateSysRole(tempData).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.handleReset()
          })
        }
      })
    },
    // 刷新
    handleReset() {
      this.$refs.basePage.getList()
    },
    handleAuthorizeMenu(row) {
      this.showMenu = true
      this.menuRow = Object.assign({}, row) // copy obj
      queryMenuIdByRoleId({ roleId: row.id }).then(response => {
        this.$nextTick(() => {
          this.$refs.menu.setCheckedNodes([])
          this.defaultChecked = response.data
        })
      })
    },
    handleAuthorizeMenuButton(roleCode) {
      this.roleCode = roleCode
      querySysMenuButtonTree().then(response => {
        this.menuButtonTree = response.data
      })
      queryMenuButtonByRoleCode(roleCode).then(response => {
        this.$refs.menuButtonTreeRef.setCheckedKeys(response.data)
      })
      this.menuButtonTreeDialogFormVisible = true
    },
    createAuthorizeMenuButton() {
      this.temButton.roleCode = this.roleCode
      this.temButton.menuButton = this.$refs.menuButtonTreeRef.getCheckedKeys().join(',')
      authorizeMenuButtonToRole(qs.stringify(this.temButton)).then(response => {
        this.menuButtonTreeDialogFormVisible = false
        this.$message({
          message: '授权按钮成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    checkAll(tab) {
      if (tab === 'menu') {
        this.$refs.menu.setCheckedNodes(this.menuList)
      } else {
        this.$refs.menuButtonTreeRef.setCheckedNodes(this.menuButtonTree)
      }
    },
    checkAth() {
      const idArr = this.$refs.menu.getCheckedKeys()
      const formData = new FormData()
      for (const k of idArr) {
        formData.append('menuId', k)
      }
      formData.append('roleId', this.menuRow.id)
      authorizeMenuToRole(formData).then(response => {
        if (response.message === 'success') {
          this.$notify({
            title: '成功',
            message: '授权成功',
            type: 'success',
            duration: 2000
          })
          this.showMenu = false
        }
      })
    }
  }
}
</script>

<style scoped>
.warning{
  text-align: center;
  font-size: 20px;
}
.el-icon-info{
  font-size: 30px;
  color: orange;
}
</style>
